package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import com.sun.tools.internal.ws.wsdl.document.schema.SchemaConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    /**
     * 添加延迟任务
     *
     * @param task
     * @return
     */
    @Override
    public Long addTask(Task task) {
        //添加任务到数据库
        boolean success = addDb(task);
        if (success) {
            //添加任务到redis
            addCache(task);
        }
        //返回ID
        return task.getTaskId();
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务到redis中
     *
     * @param task
     */
    private void addCache(Task task) {
        //当前任务类型+优先级
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取五分钟之后的时间 毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long timeInMillis = calendar.getTimeInMillis();

        //如果任务的执行时间小于等于当前时间 topic_
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //存入list
            cacheService.lLeftPush("topic_" + key, JSONObject.toJSONString(task));
        } else if (task.getExecuteTime() <= timeInMillis) {
            //当前任务的执行时间大于等于当前时间 && 小于等于预设时间 存入zset中  future_
            cacheService.zAdd("future_" + key, JSONObject.toJSONString(task), task.getExecuteTime());
        }

    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库
     *
     * @param task
     * @return
     */
    private boolean addDb(Task task) {
        boolean f = false;
        try {
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            //把时间戳转化为时间类型
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskid
            task.setTaskId(taskinfo.getTaskId());

            //保留日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            //乐观锁版本号
            taskinfoLogs.setVersion(1);
            //设置状态
            taskinfoLogs.setStatus(0);
            taskinfoLogsMapper.insert(taskinfoLogs);
            f = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return f;
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {
        boolean flag = false;
        //删除任务,更新任务日志
        Task task = updateDB(taskId, 2);
        //删除redis中的任务
        if (task != null) {
            removeRedisTask(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 删除redis中的任务
     *
     * @param task
     */
    private void removeRedisTask(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        System.out.println(new Date(System.currentTimeMillis()));
        System.out.println(new Date(task.getExecuteTime()));
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //删除现在的任务
            cacheService.lRemove("topic_" + key, 0, JSONObject.toJSONString(task));
        } else {
            //删除未来的数据
            cacheService.zRemove("future_" + key, JSONObject.toJSONString(task));
        }
    }

    /**
     * 删除任务,更新任务日志
     *
     * @param taskId
     * @param i
     * @return
     */
    private Task updateDB(Long taskId, int i) {
        //删除任务
        taskinfoMapper.deleteById(taskId);
        //更新任务日志
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(i);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        return task;
    }

    /**
     * 根据类型和优先级拉取当前任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task pull(int type, int priority) {
        Task task = null;
        try {
            String key = type + "_" + priority;
            //从redis中拉取数据
            String taskJson = cacheService.lRightPop("topic_" + key);
            if (StringUtils.isNotBlank(taskJson)) {
                //将返回的字符串格式化成对象
                task = JSONObject.parseObject(taskJson, Task.class);
                //修改数据库信息
                updateDB(task.getTaskId(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("pool task error");
        }
        return task;
    }

    /**
     * 定时刷新未来的数据
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        //分布式锁 控制分布式系统有序的去对共享资源进行操作，通过互斥来保证数据的一致性
        String futureTaskSync = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if (StringUtils.isNotBlank(futureTaskSync)) {
            //获取所有未来任务的key
            Set<String> futureKeys = cacheService.scan("future_" + "*");
            for (String futureKey : futureKeys) {
                //获取当前数据的key topic
                String topicKey = "topic_" + futureKey.split("future_")[1];
                //按照key的分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                //同步数据 未来任务不为空的话
                if (!tasks.isEmpty()) {
                    /**
                     * 未来任务的key
                     * 当前任务的key
                     * 符合条件的数据
                     */
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("成功将" + futureKey + "刷新到了" + topicKey);
                }
            }
        }
    }

    /**
     * 数据库任务定时同步到redis
     */
    @PostConstruct //每次启动服务的时候都执行一次
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        //清理缓存中的数据
        Set<String> topic = cacheService.scan("topic_" + "*");
        Set<String> future = cacheService.scan("future_" + "*");
        cacheService.delete(topic);
        cacheService.delete(future);
        //查询符合条件的任务 小于未来5分钟的数据
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        LambdaQueryWrapper<Taskinfo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.lt(Taskinfo::getExecuteTime,calendar.getTime());
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(lambdaQueryWrapper);
        //把任务添加到redis
        if (taskinfoList!=null && taskinfoList.size()>0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task=new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addCache(task);
            }
        }
        log.info("数据库任务同步redis");
    }
}
